package com.ck.juc;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.ToString;
import org.yaml.snakeyaml.events.Event;

import java.util.SortedSet;
import java.util.concurrent.*;

@NoArgsConstructor
@ToString
@Getter
public class ArrayBlockQueueDemo implements Delayed {

    private Integer index;
    private Long delay;
    private TimeUnit timeUnit;

    public ArrayBlockQueueDemo(Integer index,Long delay,TimeUnit unit) {
        this.delay = unit.toMillis(delay)+System.currentTimeMillis();
        this.timeUnit = unit;
        this.index = index;
    }

    public static void main(String[] args) throws Exception {
        ThreadLocal threadLocal = new ThreadLocal(){
            @Override
            protected Object initialValue() {
                return super.initialValue();
            }
        };
        threadLocal.set("");
        pool();
    }

    public static void pool() throws InterruptedException {
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2,
                5,
                1L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardOldestPolicy());
        for (int index =1;index <= 10;index++){
            final int ix = index;
            Thread thread = new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    String threadName = Thread.currentThread().getName();
                    System.out.println(threadName + "\t" + ix);
                    if(!"main".equals(threadName)){
                        Thread.sleep(4000);
                    }
                }
            });
            poolExecutor.execute(thread);
        }
        poolExecutor.shutdown();

    }

    public static void delay() throws InterruptedException {
        BlockingQueue<ArrayBlockQueueDemo> queue = new DelayQueue();
        queue.offer(new ArrayBlockQueueDemo(3,30L,TimeUnit.SECONDS));
        queue.offer(new ArrayBlockQueueDemo(2,1L, TimeUnit.MINUTES));
        System.out.println(queue.take());
        System.out.println(queue.take());
    }


    /**
     * ArrayBlockQueue
     */
    private static void array() throws InterruptedException {
        BlockingQueue<String> blockingDeque = new ArrayBlockingQueue<>(3);
        blockingDeque.put("1");
        blockingDeque.put("3");
        blockingDeque.put("2");
        blockingDeque.put("4");
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(delay-System.currentTimeMillis(),TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        ArrayBlockQueueDemo queueDemo = (ArrayBlockQueueDemo) o;
        return (int) (this.getDelay() - queueDemo.getDelay());
    }
}
